<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

// 管理员权限检查（这里简化处理，实际应该有完整的角色权限系统）
function checkAdminAuth() {
    global $auth;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    // 这里可以添加管理员权限检查
    // if (!$user['is_admin']) {
    //     Response::error('权限不足');
    // }
    return $user;
}

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'get_config':
                // 获取配置
                $configKey = $_GET['config_key'] ?? null;
                if ($configKey) {
                    $config = $db->fetchOne("SELECT * FROM museum_config WHERE config_key = ?", [$configKey]);
                    if ($config) {
                        $value = $config['config_value'];
                        // 根据类型转换值
                        switch ($config['config_type']) {
                            case 'number':
                                $value = (int)$value;
                                break;
                            case 'boolean':
                                $value = (bool)$value;
                                break;
                            case 'json':
                                $value = json_decode($value, true);
                                break;
                        }
                        Response::success(['value' => $value, 'type' => $config['config_type']], '获取成功');
                    } else {
                        Response::error('配置不存在');
                    }
                } else {
                    // 获取所有配置
                    $configs = $db->fetchAll("SELECT * FROM museum_config ORDER BY config_key");
                    $result = [];
                    foreach ($configs as $config) {
                        $value = $config['config_value'];
                        // 根据类型转换值
                        switch ($config['config_type']) {
                            case 'number':
                                $value = (int)$value;
                                break;
                            case 'boolean':
                                $value = (bool)$value;
                                break;
                            case 'json':
                                $value = json_decode($value, true);
                                break;
                        }
                        $result[$config['config_key']] = [
                            'value' => $value,
                            'type' => $config['config_type'],
                            'description' => $config['description']
                        ];
                    }
                    Response::success($result, '获取成功');
                }
                break;
                
            case 'get_schedule':
                // 获取开馆时间表
                $schedule = $db->fetchAll("SELECT * FROM museum_schedule ORDER BY day_of_week");
                Response::success($schedule, '获取成功');
                break;
                
            case 'get_time_slots':
                // 获取时段列表
                $slots = $db->fetchAll("SELECT * FROM museum_time_slots WHERE is_active = 1 ORDER BY sort_order");
                Response::success($slots, '获取成功');
                break;
                
            case 'get_closure_dates':
                // 获取闭馆日期
                $startDate = $_GET['start_date'] ?? date('Y-m-d');
                $endDate = $_GET['end_date'] ?? date('Y-m-d', strtotime('+1 year'));
                
                $closures = $db->fetchAll("
                    SELECT * FROM museum_closure_dates 
                    WHERE is_active = 1 
                    AND (
                        (closure_type = 'once' AND closure_date BETWEEN ? AND ?) 
                        OR closure_type = 'yearly'
                    )
                    ORDER BY closure_date
                ", [$startDate, $endDate]);
                
                Response::success($closures, '获取成功');
                break;
                
            case 'check_availability':
                // 检查某日期是否可预约
                $visitDate = $_GET['date'] ?? date('Y-m-d');
                $timeSlotId = $_GET['time_slot_id'] ?? null;
                
                $availability = checkDateAvailability($visitDate, $timeSlotId);
                Response::success($availability, '检查完成');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $user = checkAdminAuth();
        
        switch ($action) {
            case 'update_config':
                // 更新配置
                if (!isset($input['config_key']) || !isset($input['config_value'])) {
                    Response::error('缺少必要参数');
                }
                
                $configKey = $input['config_key'];
                $configValue = $input['config_value'];
                $configType = $input['config_type'] ?? 'string';
                
                // 验证配置值
                switch ($configType) {
                    case 'number':
                        if (!is_numeric($configValue)) {
                            Response::error('配置值必须是数字');
                        }
                        break;
                    case 'boolean':
                        $configValue = $configValue ? '1' : '0';
                        break;
                    case 'json':
                        if (is_array($configValue) || is_object($configValue)) {
                            $configValue = json_encode($configValue);
                        }
                        break;
                }
                
                $result = $db->update('museum_config', [
                    'config_value' => (string)$configValue,
                    'config_type' => $configType,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'config_key = :config_key', ['config_key' => $configKey]);
                
                if ($result) {
                    Response::success(['config_key' => $configKey, 'config_value' => $configValue], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'update_schedule':
                // 更新开馆时间
                if (!isset($input['day_of_week'])) {
                    Response::error('缺少星期参数');
                }
                
                $dayOfWeek = (int)$input['day_of_week'];
                $isOpen = isset($input['is_open']) ? (int)$input['is_open'] : 1;
                $openTime = $input['open_time'] ?? null;
                $closeTime = $input['close_time'] ?? null;
                $maxVisitors = (int)($input['max_visitors'] ?? 0);
                
                $result = $db->update('museum_schedule', [
                    'is_open' => $isOpen,
                    'open_time' => $openTime,
                    'close_time' => $closeTime,
                    'max_visitors' => $maxVisitors,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'day_of_week = :day_of_week', ['day_of_week' => $dayOfWeek]);
                
                if ($result) {
                    Response::success(['day_of_week' => $dayOfWeek], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'add_time_slot':
                // 添加时段
                if (!isset($input['slot_name']) || !isset($input['start_time']) || !isset($input['end_time'])) {
                    Response::error('缺少必要参数');
                }
                
                $slotId = $db->insert('museum_time_slots', [
                    'slot_name' => $input['slot_name'],
                    'start_time' => $input['start_time'],
                    'end_time' => $input['end_time'],
                    'max_visitors' => (int)($input['max_visitors'] ?? 50),
                    'is_active' => (int)($input['is_active'] ?? 1),
                    'sort_order' => (int)($input['sort_order'] ?? 0)
                ]);
                
                if ($slotId) {
                    Response::success(['id' => $slotId], '添加成功');
                } else {
                    Response::error('添加失败');
                }
                break;
                
            case 'add_closure_date':
                // 添加闭馆日期
                if (!isset($input['closure_date'])) {
                    Response::error('缺少日期参数');
                }
                
                $closureId = $db->insert('museum_closure_dates', [
                    'closure_date' => $input['closure_date'],
                    'closure_type' => $input['closure_type'] ?? 'once',
                    'reason' => $input['reason'] ?? '',
                    'is_active' => (int)($input['is_active'] ?? 1)
                ]);
                
                if ($closureId) {
                    Response::success(['id' => $closureId], '添加成功');
                } else {
                    Response::error('添加失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        $user = checkAdminAuth();
        
        switch ($action) {
            case 'update_time_slot':
                // 更新时段
                if (!isset($input['id'])) {
                    Response::error('缺少时段ID');
                }
                
                $slotId = (int)$input['id'];
                $updateData = [];
                
                if (isset($input['slot_name'])) $updateData['slot_name'] = $input['slot_name'];
                if (isset($input['start_time'])) $updateData['start_time'] = $input['start_time'];
                if (isset($input['end_time'])) $updateData['end_time'] = $input['end_time'];
                if (isset($input['max_visitors'])) $updateData['max_visitors'] = (int)$input['max_visitors'];
                if (isset($input['is_active'])) $updateData['is_active'] = (int)$input['is_active'];
                if (isset($input['sort_order'])) $updateData['sort_order'] = (int)$input['sort_order'];
                
                $updateData['updated_at'] = date('Y-m-d H:i:s');
                
                $result = $db->update('museum_time_slots', $updateData, 'id = :id', ['id' => $slotId]);
                
                if ($result) {
                    Response::success(['id' => $slotId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        $user = checkAdminAuth();
        
        switch ($action) {
            case 'delete_time_slot':
                // 删除时段
                $slotId = (int)($_GET['id'] ?? 0);
                if (!$slotId) {
                    Response::error('缺少时段ID');
                }
                
                $result = $db->delete('museum_time_slots', 'id = ?', [$slotId]);
                
                if ($result) {
                    Response::success(['id' => $slotId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            case 'delete_closure_date':
                // 删除闭馆日期
                $closureId = (int)($_GET['id'] ?? 0);
                if (!$closureId) {
                    Response::error('缺少闭馆日期ID');
                }
                
                $result = $db->delete('museum_closure_dates', 'id = ?', [$closureId]);
                
                if ($result) {
                    Response::success(['id' => $closureId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 检查日期可用性的函数
function checkDateAvailability($visitDate, $timeSlotId = null) {
    global $db;
    
    // 检查日期格式
    $dateObj = DateTime::createFromFormat('Y-m-d', $visitDate);
    if (!$dateObj) {
        return ['available' => false, 'reason' => '日期格式无效'];
    }
    
    $today = date('Y-m-d');
    if ($visitDate < $today) {
        return ['available' => false, 'reason' => '不能预约过去的日期'];
    }
    
    // 检查预约提前天数限制
    $advanceConfig = $db->fetchOne("SELECT config_value FROM museum_config WHERE config_key = 'advance_booking_days'");
    $advanceDays = (int)($advanceConfig['config_value'] ?? 7);
    $maxDate = date('Y-m-d', strtotime("+{$advanceDays} days"));
    if ($visitDate > $maxDate) {
        return ['available' => false, 'reason' => "只能预约{$advanceDays}天内的日期"];
    }
    
    // 检查是否为休息日
    $dayOfWeek = date('N', strtotime($visitDate)); // 1=周一, 7=周日
    $schedule = $db->fetchOne("SELECT * FROM museum_schedule WHERE day_of_week = ?", [$dayOfWeek]);
    if (!$schedule || !$schedule['is_open']) {
        return ['available' => false, 'reason' => '该日期为休息日'];
    }
    
    // 检查特殊闭馆日期
    $closure = $db->fetchOne("
        SELECT * FROM museum_closure_dates 
        WHERE is_active = 1 
        AND (
            (closure_type = 'once' AND closure_date = ?) 
            OR (closure_type = 'yearly' AND DATE_FORMAT(?, '%m-%d') = DATE_FORMAT(closure_date, '%m-%d'))
        )
    ", [$visitDate, $visitDate]);
    
    if ($closure) {
        return ['available' => false, 'reason' => '该日期为闭馆日：' . $closure['reason']];
    }
    
    // 检查预约人数限制
    if ($timeSlotId) {
        $slot = $db->fetchOne("SELECT * FROM museum_time_slots WHERE id = ? AND is_active = 1", [$timeSlotId]);
        if (!$slot) {
            return ['available' => false, 'reason' => '时段不存在或未启用'];
        }
        
        $reserved = $db->fetchOne("
            SELECT COALESCE(SUM(visitor_count), 0) as total 
            FROM reservations 
            WHERE visit_date = ? AND time_slot_id = ? AND status IN ('pending', 'confirmed')
        ", [$visitDate, $timeSlotId]);
        
        $availableSlots = $slot['max_visitors'] - ($reserved['total'] ?? 0);
        
        return [
            'available' => $availableSlots > 0,
            'available_slots' => $availableSlots,
            'max_visitors' => $slot['max_visitors'],
            'slot_info' => $slot
        ];
    }
    
    return ['available' => true, 'schedule' => $schedule];
}
?>